package com.rongke.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.commons.JsonResp;
import com.rongke.model.BuyTogetherGoods;
import com.rongke.model.Goods;
import com.rongke.model.UserCollection;
import com.rongke.service.BuyTogetherGoodsService;
import com.rongke.service.GoodsService;
import com.rongke.service.UserCollectionService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version : Ver 1.0
 * @UserCollectionController
 * @收藏Controller
 */
@RestController
@RequestMapping(value = "/api/userCollection")
@Transactional
public class UserCollectionController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private UserCollectionService userCollectionService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private BuyTogetherGoodsService buyTogetherGoodsService;

    /**
     * @param userCollection
     * @return 返回值JsonResp
     * @添加收藏
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResp addUserCollection(@RequestBody UserCollection userCollection) {
        log.debug("添加收藏");
        if (null == userCollection.getGoodsId() || null == userCollection.getMuserId() || null == userCollection.getCollectionTag()
                || 0 == userCollection.getMuserId() || 0 == userCollection.getGoodsId())
            return JsonResp.toFail("参数不能为空");
        userCollection.setGmtDatetime(new Date());
        userCollectionService.insert(userCollection);
        return JsonResp.ok(userCollection);
    }

    /**
     * @param userCollection
     * @return 返回值JsonResp
     * @添加、取消收藏
     */
    @RequestMapping(value = "/toggle", method = RequestMethod.POST)
    public JsonResp toggleUserCollection(@RequestBody UserCollection userCollection) {
        log.debug("添加、取消收藏");
        Long muserId = userCollection.getMuserId();
        Long goodsId = userCollection.getGoodsId();
        Integer tag = userCollection.getCollectionTag();
        if (null == goodsId || null == muserId || null == tag || 0 == muserId || 0 == goodsId)
            return JsonResp.toFail("参数不能为空");
        Map map = new HashMap();
        Integer isCollected= (Integer) getIsUserEverCollected(muserId,goodsId,tag).getData();
        //当前是否收藏
        Integer curIsCollected;
        String msg="";
        //1 已收藏 0 未收藏
        if(isCollected==1){
            //取消收藏action
            EntityWrapper<UserCollection> ew=new EntityWrapper<>(userCollection);
            userCollectionService.delete(ew);
            curIsCollected=0;
            msg="取消收藏成功";
        }else{
            //添加收藏action
            userCollection.setGmtDatetime(new Date());
            userCollectionService.insert(userCollection);
            curIsCollected=1;
            msg="收藏成功";
        }
        map.put("userCollection", userCollection);
        map.put("curIsCollected", curIsCollected);
        map.put("msg", msg);
        return JsonResp.ok(map);
    }

    /**
     * @param userCollection
     * @return 返回值JsonResp
     * @修改收藏
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResp updateUserCollection(@RequestBody UserCollection userCollection) {
        log.debug("修改收藏");
        userCollectionService.updateById(userCollection);
        return JsonResp.ok(userCollection);
    }

    /**
     * @param id
     * @return 返回值JsonResp
     * @根据id查找收藏
     */
    @RequestMapping(value = "/selectOne", method = RequestMethod.GET)
    public JsonResp selectUserCollection(Long id) {
        log.debug("查找收藏");
        UserCollection userCollection = userCollectionService.selectById(id);
        return JsonResp.ok(userCollection);
    }

    /**
     * @return
     * @分页获取某一用户的收藏商品列表
     */
    @RequestMapping(value = "/selectCollectionByUserId", method = RequestMethod.GET)
    public JsonResp selectCollectionGoodsByUserId(Long userId,Integer tag, Page page) {
        log.debug("获取某一用户的收藏商品");
        //收藏商品
        if(tag==0){
            EntityWrapper<Goods> ew = new EntityWrapper<>();
            ew.where("goods.id in (select goods_id from user_collection uc where muser_id ={0} and uc.collection_tag={1})", userId,tag);
            page = goodsService.selectPage(page, ew);
        }
        //收藏拼团
        if(tag==1){
            EntityWrapper<UserCollection> ew=new EntityWrapper<>();
            ew.setSqlSelect("goods_id goodsIds");
            ew.eq("muser_id",userId);
            ew.eq("collection_tag",tag);
            List<Object> goodsIdList=userCollectionService.selectObjs(ew);
            StringBuilder goodsIds=new StringBuilder();
            String goodsIdstr="";
            if(!goodsIdList.isEmpty()){
                goodsIdList.forEach(e->{
                    goodsIds.append(",").append(e.toString());
                });
                goodsIdstr=goodsIds.toString().substring(1);
                Map map=new HashMap();
                map.put("goodsIds",goodsIdstr);
                map.put("startIndex",(page.getCurrent()-1)*page.getSize());
                map.put("size",page.getSize());
                List<BuyTogetherGoods> goodsPage = buyTogetherGoodsService.selectTogGoodsList(map);
                int total=buyTogetherGoodsService.selectCount(null);
                page.setRecords(goodsPage);
                page.setTotal(total);
            }
        }
        return JsonResp.ok(page);
    }

    /**
     * @return
     * @获取某一用户的收藏商品列表
     */
    @RequestMapping(value = "/selectExpCollectionByUserId", method = RequestMethod.GET)
    public JsonResp selectExpCollectionByUserId(Long userId) {
        log.debug("获取某一用户的收藏商品");
        EntityWrapper<Goods> ew = new EntityWrapper<>();
        ew.where("goods.id in (select goods_id from user_collection uc where muser_id ={0} and uc.collection_tag=0)", userId);
        List<Goods> goodsPage = goodsService.selectList(ew);
        return JsonResp.ok(goodsPage);
    }

/*    *//**
     * @获取某一用户的收藏拼团列表
     * @return
     *//*
    @RequestMapping(value = "/selectCollectionGroupBuyingByUserId", method = RequestMethod.GET)
    public JsonResp selectCollectionGroupBuyingByUserId(Long userId, Page page) {
        log.debug("获取某一用户的收藏拼团");
        EntityWrapper<Goods> ew = new EntityWrapper<>();
        ew.where("goods.id in (select goods_id from user_collection uc where muser_id ={0} and uc.collection_tag=0)", userId);

        Page<Goods> goodsPage = goodsService.selectPage(page, ew);
        Map<String, Object> groupBuyingMap = new HashMap<>();

        待定！
    }*/

    /**
     * 获取是否收藏
     *
     * @param muserId
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/getIsUserEverCollected", method = RequestMethod.GET)
    public JsonResp getIsUserEverCollected(Long muserId, Long goodsId, Integer tag) {
        log.debug("获取是否收藏");
        if (null == muserId || null == goodsId || null == tag)
            return JsonResp.toFail("参数不能为空");
        EntityWrapper<UserCollection> ew = new EntityWrapper<>();
        ew.eq("muser_id", muserId)
                .eq("goods_id", goodsId)
                .eq("collection_tag", tag);
        Integer count = userCollectionService.selectCount(ew);
        if (count > 0) {
            return JsonResp.ok(1);
        } else {
            return JsonResp.ok(0);
        }

    }

}
